package com.maimao.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.maimao.core.enums.AuthEnum;
import com.maimao.core.model.resp.Result;
import com.maimao.zuul.service.AuthService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 身份校验过虑器
 *
 * @author Administrator
 * @version 1.0
 **/

public abstract class AbstractLoginFilter extends ZuulFilter {

    @Autowired
    AuthService authService;


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //返回true表示要执行此过虑器
        return true;
    }

    /**
     * chuile
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        //得到request
        HttpServletRequest request = requestContext.getRequest();
        String requestURI = request.getRequestURI();

        logUri(requestURI);
        if (getAllowedPaths().contains(request.getRequestURI())) {
            return null;
        }
        if (requestURI.indexOf("/search/goods") > -1 || requestURI.indexOf("/dev-api/maimao_goods/goods/goods/detail") > -1) {
            return null;
        }
        //得到response
        HttpServletResponse response = requestContext.getResponse();
        //取cookie中的身份令牌
        String tokenFromCookie = authService.getTokenFromCookie(request, getCookieKey());
        Result refuseRes = new Result(AuthEnum.NOT_AUTH.getCode(), false, AuthEnum.NOT_AUTH.getMessage());
        if (StringUtils.isEmpty(tokenFromCookie)) {
            //拒绝访问
            refuse(requestContext, response, refuseRes);
            return null;
        }
        if (request.getRequestURI().equals("/dev-api/auth/get-jwt")) {
            return null;
        }
        String jwt = authService.getJwtFromHeader(request);
        if (StringUtils.isEmpty(jwt)) {
            refuse(requestContext, response, refuseRes);
        }
       /* boolean res = authService.checkRepeat(jwt, tokenFromCookie);
        if (!res) {
            //已在别处登录
            refuse(requestContext, response, new Result(AuthEnum.LOGIN_REPEAT.getCode(), false, AuthEnum.LOGIN_REPEAT.getMessage()));
        }*/
        //从redis取出jwt的过期时间
        if (authService.isExpire(tokenFromCookie)) {
            //拒绝访问
            refuse(requestContext, response, refuseRes);
        }

        return null;
    }


    /**
     * 拒绝访问
     *
     * @param requestContext
     * @param response
     */
    private void refuse(RequestContext requestContext, HttpServletResponse response, Result result) {
        //拒绝访问
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(200);
        //构建响应的信息
        //转成json
        String jsonString = JSON.toJSONString(result);
        requestContext.setResponseBody(jsonString);
        //转成json，设置contentType
        response.setContentType("application/json;charset=utf-8");
    }


    public abstract String getCookieKey();
    public abstract void logUri(String uri);

    public abstract List<String> getAllowedPaths();

    public AuthService getAuthService() {
        return authService;
    }

    public void setAuthService(AuthService authService) {
        this.authService = authService;
    }


}
